#include "databus.h"
#include "string_operation.h"


static int data_bus_buff_index = 0;
static int data_bus_index = 0;

static unsigned char DATA_BUS_BUFF[DATA_BUS_BUFF_SIZE] = {};


DATA_BUS data_bus[DATA_BUS_DATA_SIZE] = {};

int data_bus_add_data(char *name, char type, int length, void *trigger) {
    int result = 0;
    if (data_bus_index < DATA_BUS_DATA_SIZE && (data_bus_buff_index + length) < DATA_BUS_BUFF_SIZE) {
        string_copy(name, data_bus[data_bus_index].name);
        data_bus[data_bus_index].trigger = trigger;
        data_bus[data_bus_index].length = length;
        data_bus[data_bus_index].type = type;
        data_bus[data_bus_index].index = data_bus_buff_index;

        result = data_bus_index;
        data_bus_buff_index += length;
        data_bus_index++;
    }
    return result;
}

int data_bus_find_data_index_by_name(char *name) {
    int index;
    for (index = 0; index < DATA_BUS_DATA_SIZE; index++) {
        if (data_bus[index].type) {
            if (string_equal(data_bus[index].name, name)) {
                break;
            }
        } else {
            break;
        }
    }
    return index;
}


int data_bus_change_data_by_name(char *name, char *value) {

    return data_bus_change_data_by_index(data_bus_find_data_index_by_name(name), value);
}

int data_bus_change_data_by_index(int index, char *value) {
    char need_trigger = 0x00;
    int value_index;
    for (value_index = 0; value_index < data_bus[index].length && *value != '\0'; value_index++) {
        if (DATA_BUS_BUFF[data_bus[index].index] != *value) {
            need_trigger = 0x0f;
            DATA_BUS_BUFF[data_bus[index].index] = *value;
        }
        value++;
    }
    if (need_trigger) {
        ((void *(*)(DATA_BUS ltv)) (data_bus[index].trigger))(data_bus[index]);
    }

    return data_bus_index;
}


DATA_BUS data_bus_get_data_by_name(char *name) {
    return data_bus_get_data_by_index(data_bus_find_data_index_by_name(name));
}

DATA_BUS data_bus_get_data_by_index(int index) {
    DATA_BUS data = {0};
    if (index >= 0 && index < DATA_BUS_DATA_SIZE) {
        data = data_bus[index];
    }
    return data;
}


char *data_bus_get_data_value_by_name(char *name) {
    return (char *) &DATA_BUS_BUFF[data_bus[data_bus_find_data_index_by_name(name)].index];
}